package com.eshop.xss;

import java.util.regex.Matcher;
import java.util.Iterator;
import java.util.regex.Pattern;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.FilterChain;
import javax.servlet.ServletResponse;
import javax.servlet.ServletRequest;
import javax.servlet.ServletException;
import cn.hutool.core.util.StrUtil;
import javax.servlet.FilterConfig;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;

public class XssFilter implements Filter
{
    public List<String> excludes;
    public boolean enabled;
    
    public XssFilter() {
        this.excludes = new ArrayList<String>();
        this.enabled = false;
    }
    
    public void init(final FilterConfig filterConfig) throws ServletException {
        final String tempExcludes = filterConfig.getInitParameter("excludes");
        final String tempEnabled = filterConfig.getInitParameter("enabled");
        if (StrUtil.isNotEmpty((CharSequence)tempExcludes)) {
            final String[] url = tempExcludes.split(",");
            for (int i = 0; url != null && i < url.length; ++i) {
                this.excludes.add(url[i]);
            }
        }
        if (StrUtil.isNotEmpty((CharSequence)tempEnabled)) {
            this.enabled = Boolean.valueOf(tempEnabled);
        }
    }
    
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest req = (HttpServletRequest)request;
        final HttpServletResponse resp = (HttpServletResponse)response;
        if (this.handleExcludeURL(req, resp)) {
            chain.doFilter(request, response);
            return;
        }
        final XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest)request);
        chain.doFilter((ServletRequest)xssRequest, response);
    }
    
    private boolean handleExcludeURL(final HttpServletRequest request, final HttpServletResponse response) {
        if (!this.enabled) {
            return true;
        }
        if (this.excludes == null || this.excludes.isEmpty()) {
            return false;
        }
        final String url = request.getServletPath();
        for (final String pattern : this.excludes) {
            final Pattern p = Pattern.compile("^" + pattern);
            final Matcher m = p.matcher(url);
            if (m.find()) {
                return true;
            }
        }
        return false;
    }
    
    public void destroy() {
    }
}
